// 实现jsonp
// script标签不遵循同源协议，可以用来进行跨域请求，优点就是兼容性好但仅限于GET请求
const jsonp = (url, data = {}, cb = "callback") => {
  let searchStr = url.indexOf("?") === -1 ? "?" : "&";
  for (const key in data) {
    searchStr += `${key}=${data[key]}&`;
  }
  searchStr += `callback=${cb}`;
  url = url + searchStr;

  const script = document.createElement("script");
  script.src = url;
  document.body.appendChild(script); // append 到页面中添加到页面就立刻发起请求

  return new Promise((resolve, reject) => {
    window[cb] = (data) => {
      try {
        resolve(data);
      } catch (error) {
        reject(error);
      } finally {
        script.parentNode.removeChild(script); // 移除 script
      }
    };
  });
};

// 测试
jsonp("https://photo.sina.cn/aj/index", { page: 1, cate: "recommend" }).then(
  (res) => {
    console.log(res);
  }
);
